package cn.javacart.jopencart.interceptor;

import java.util.Map;

import cn.javacart.jopencart.controller.JOpencartController;
import cn.javacart.jopencart.library.ConfigService;
import cn.javacart.jopencart.library.SessionConfigService;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;

/**
 * 初始化
 * @author farmer
 *
 */
public class JOpencartInitConfigInterceptor implements Interceptor{

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		SessionConfigService.init(controller.getSession());	//初始化，设置session
		Map<String, Object> configMap = SessionConfigService.getConfigMap();	//从session中获取配置信息
		if(configMap == null){	//首次进入系统
			String language =  null;//从Session中读取语言
			if(StrKit.notBlank((String)SessionConfigService.get("language"))){
				language = SessionConfigService.get("language");
			}else if(StrKit.notBlank((String)controller.getCookie("language"))){
				language = controller.getCookie("language");
			}
			if(Db.queryLong("select count(1) from  joc_language t where t.code = ? and t.status = ?",language,1) == 0){
				language =  (String)ConfigService.getInstance().get("config_language");				
			}
			SessionConfigService.set("config_language_id", Db.queryInt("select language_id from joc_language t where t.code =  ?", language));
			SessionConfigService.set("config_language", language);
			controller.setCookie("language", language, 60 * 60 * 24 * 30);
		}
		if(controller instanceof JOpencartController){
			((JOpencartController) controller).setRoute(controller.getPara("route","common/home"));
		}
		inv.invoke();
	}

}
